package com.laikan.reader.bookfriend.net;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.reader.bookfriend.utils.LogUtils;
import com.socks.library.KLog;

import java.util.Map;

/**
 * Created by lingyt on 2016/11/3.
 * 自定义网络请求类For 个人主页
 */
public class NetApiHelper {
    public static final String TAG = "NetApiHelper";
    public static final String HOST_API = "http://www.laikan.com/%s";//外网环境
//    public static final String LOCAL_API = "http://101.201.77.139:8080/%s";//内网
//    public static final String LOCAL_API = "http://112.124.22.238:8081/%s";//内网
    public static final String LOCAL_API = "http://api.motie.com/%s";//内网环境


    public static boolean isUserLocal = true;//内外网开关


    private static NetApiHelper mInstence = new NetApiHelper();
    private Gson mGson;
    protected BaseCallback mCallback;

    private NetApiHelper(){
        mGson = new Gson();
    }

    public static NetApiHelper getInstence(){
        return mInstence;
    }

    private RequestListener mHandler = new RequestListener() {
        @Override
        public void onPreExecute() {
            mCallback.onPreExecute();
        }

        @Override
        public void onSuccess(HttpResponse httpResponse) {
            String resultStr = httpResponse.responseContent;
            KLog.w(TAG,"响应正文字符串：\n        "+resultStr);
            if (mCallback.mType == String.class){
                mCallback.onSuccess(httpResponse,resultStr);
            }
            else {
                try {
                    Object obj = mGson.fromJson(resultStr, mCallback.mType);
                    KLog.w(TAG,"Json数据解析成功，初始化数据...........");
                    mCallback.onSuccess(httpResponse,obj);
                }catch (JsonParseException e) { // Json解析的错误
                    KLog.w(TAG,"Json数据解析失败，JsonParseException:" + e.getMessage());
                    mCallback.onError(null);
                }
            }
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            KLog.w(TAG,"服务器返回数据出错："+errorHandler.geErrortMessage());
            mCallback.onError(errorHandler);
        }

        @Override
        public void onFinish() {
            KLog.w(TAG,"------------------------------数据请求结束-------------------------");
            KLog.w(TAG,"--");
            KLog.w(TAG,"--");
            KLog.w(TAG,"--");
            KLog.w(TAG,"--");
            mCallback.onFinish();
        }
    };


    /**
     * 执行Get请求
     * @param partUrl
     * @param params
     * @param callback
     */
    public void doGet(String partUrl, Map<String, String> params, BaseCallback callback){
        KLog.w(TAG,"开始执行get请求.....");
        this.mCallback = callback;
        Requester requester = new Requester();
        requester.setUrl(getAbsoluteApiUrl(partUrl));
        requester.setMapBody(params);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, mHandler);
    }

    /**
     * 执行Post请求
     * @param partUrl
     * @param params
     * @param callback
     */
    public void doPost(String partUrl,Map<String, String> params, BaseCallback callback){

        KLog.w(TAG,"开始执行post请求..............");
        this.mCallback=callback;
        Requester requester = new Requester();
        requester.setUrl(getAbsoluteApiUrl(partUrl));
        requester.setMapBody(params);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, mHandler);
    }


    /**
     * 取消所有的网络任务
     */
    public void cancelAllRequest() {
        KLog.w(TAG,"取消所有网络任务..............volley");
        HttpApiRequestEngine.getInstance().cancelAllRequest();
    }

    /**
     * 获取完整的api路径
     * @param partUrl
     * @return
     */
    public static String getAbsoluteApiUrl(String partUrl){
        String url = null;
        if (isUserLocal){
            KLog.w(TAG,"请注意。。网络环境为测试环境！！！！！！！！");
            url = String.format(LOCAL_API,partUrl);
        }else{
            KLog.w(TAG,"请注意。。网络环境为正式环境！！！！！！！");
            url = String.format(HOST_API,partUrl);
        }
        KLog.w(TAG,"数据请求地址："+url);
        return url;
    }

    public static void log(String msg){
        LogUtils.log(TAG+"----"+msg);
    }

}
